package grouper;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;

import database.*;
import database.table.DBTableData;
import datagram.*;

public class SimpleGrouper extends Grouper {
	private double tolerance;
	
	public SimpleGrouper( DBTableData data, double tolerance ) {
		super(data);
		this.tolerance = tolerance;
	}
	
	public void group() {
		ArrayList<Datagram> datagramList = new ArrayList<Datagram>();
		BufferedImage image;
		Datagram element;
		int gid, gcol;
		double diff, mindiff;
		
		// Create group column, or select it if existant
		gcol = data.addColumn("Group", Integer.class);
		if (gcol == -1)
			gcol = data.getColumnIndex("Group");
		
		// Define group for each element
		for (int row = 0; row < data.getRowCount(); row++) {
			gid = -1;
			
			try {
				// Read pivot element
				image = ImageIO.read(data.getBlobStreamAt(row, "image"));
				element = new Matchgram( image, 200, Matchgram.METHOD);
				
				// Find closest existant datagram
				mindiff = -1;
				for (int d = 0; d < datagramList.size(); d++) {
					diff = datagramList.get(d).difference(element);
					if (mindiff < 0 || diff < mindiff) {
						gid = d;
						mindiff = diff;
					}
				}
				
				// If no group found or closest datagram is too different, create new group
				if (gid == -1 || mindiff > tolerance) {
					datagramList.add(element);
					gid = datagramList.size() - 1;
				}
			} catch (IOException e) {
				//System.out.println("ERROR: could not read image for id = " + data.data.get(row).get(0));
				System.out.println(e.getMessage());
			}
			
			data.setValueAt(gid, row, gcol);
			System.out.println(row + "/" + data.getRowCount());
		}
		
		data.sort( gcol );
	}

}
